<?php
/**
 * Created by PhpStorm.
 * User: dragon
 * Date: 2015/11/20
 * Time: 13:26
 */

namespace Wap\Controller;
use Common\Controller\CommonController;
use Common\Org\Pay\wxpay\unit\CLogFileHandler;
use Common\Org\Pay\wxpay\unit\Log;
use Common\Org\Pay\wxpay\unit\JsApiPay;
use Common\Org\Pay\wxpay\lib\WxPayUnifiedOrder;
use Common\Org\Pay\wxpay\lib\WxPayApi;

class WxPayController extends CommonController
{
    private $model;

    protected function _initialize(){
        parent::_initialize();
        $this->model = D('Wap/Order');
    }

    public function index(){
        //初始化日志
        $logHandler= new CLogFileHandler("./wxpaylogs/".date('Y-m-d').'.log');
        Log::Init($logHandler, 15);

        //获取用户openid
        $tools = new JsApiPay();
        $openId = $tools->GetOpenid();

        Log::INFO('获取OPENID:'.$openId);

        //订单数据处理
        $req_data = I('get.');
        $uid = $this->uid;
        $order_id = $req_data['orderid'];

        $detail = $this->model->detail($order_id);
        if(empty($detail) || $detail['status'] != 1 || $detail['uid'] != $this->uid) toErrorPage();

        $shopDetail = D('Common/Shop')->detail($detail['shop_id']);
        $attach = $detail['orderno'].':'.$shopDetail['title'].':'.$uid; //订单号及用户ID

        //异常处理
        set_exception_handler(function($exception){
            toErrorPage();exit;
        });

        //统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody(SITE_NAME.'('.$shopDetail['title'].')');
        $input->SetAttach($attach);
        $input->SetOut_trade_no($detail['orderno']);
        $input->SetTotal_fee(floatval($detail['paytotal']) * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("wxpay");
        $input->SetNotify_url(SITE_URL."/WxPayNotify");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);

        $order = WxPayApi::unifiedOrder($input);
        Log::INFO('下单:'.var_export($order,true));

        $jsApiParameters = $tools->GetJsApiParameters($order);

        Log::INFO('JSAPI参数'.$jsApiParameters);

        $this->assign('jsApiParameters',$jsApiParameters);
        $this->assign($req_data);
        $this->assign('seo_title','微信支付');
        $this->assign('orderid',$order_id);
        $this->display();
    }

    public function notify(){

    }
}